package com.sunlee.admin.api.module.job.template.impl;

import com.sunlee.admin.api.module.job.template.CrawResourceCategoryTemplate;
import com.sunlee.admin.api.util.JsoupUtil;
import com.sunlee.admin.api.module.job.template.context.CrawResourceCategoryContext;
import com.sunlee.common.core.utils.StringUtil;
import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.service.entity.ThirdCategoryEntity;
import com.sunlee.common.service.enums.StatusEnum;
import com.sunlee.common.service.enums.ThirdFileSourceEnum;
import com.sunlee.common.service.service.ThirdCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 爬取第一PPT的全部分类
 *
 * @author sunlee
 */
@Slf4j
@Service
public class CrawResourceCategoryFirstPpt extends CrawResourceCategoryTemplate {

    public static final String LEVEL1_URL = "https://www.1ppt.com";

    public static final String LEVEL2_URL = "https://www.1ppt.com/{0}";

    @Autowired
    private ThirdCategoryService thirdCategoryService;

    @Override
    protected void init(CrawResourceCategoryContext context) {
        context.setSource(ThirdFileSourceEnum.FIRST_PPT.getCode());
    }

    protected Document requestGet(String url) {
        try {
            Document document = JsoupUtil.connectByGet(url);
            if (Objects.isNull(document)) {
                throw new BusinessException("返回数据异常");
            }
            return document;
        } catch (Exception e) {
            log.error("第一PPT爬取分类异常：{}", url, e);
            throw new BusinessException(e.getMessage());
        }
    }

    public static void main(String[] args) {
        CrawResourceCategoryContext context = new CrawResourceCategoryContext();
        CrawResourceCategoryFirstPpt crawCategoryFirstPpt = new CrawResourceCategoryFirstPpt();
        crawCategoryFirstPpt.process(context);
    }

    @Override
    protected void handleLeve1Category(CrawResourceCategoryContext context) {
        // 爬取一级分类
        List<ThirdCategoryEntity> oneLevelCategoryList = new ArrayList<>();

        // 发起请求，获取并解析document
        Document document = requestGet(LEVEL1_URL);
        Element navMenu = document.getElementById("navMenu");
        Elements aListEle = navMenu.select("li").select("a");
        for (Element aEle : aListEle) {
            ThirdCategoryEntity thirdCategory = new ThirdCategoryEntity();
            thirdCategory.setSource(context.getSource());
            thirdCategory.setLevel(1);
            thirdCategory.setPid(0L);
            thirdCategory.setStatus(StatusEnum.VALID.getCode());
            thirdCategory.setCategoryId(aEle.attributes().get("href").replace("/", ""));
            thirdCategory.setName(aEle.text());
            oneLevelCategoryList.add(thirdCategory);
        }

        // 填充
        context.setThirdCategoryList(oneLevelCategoryList);

        // 保存
        saveOrUpdate(context);
    }

    @Override
    protected void handleLeve2Category(CrawResourceCategoryContext context) {
        List<ThirdCategoryEntity> twoLevelCategoryList = new ArrayList<>();

        // 爬取二级分类
        for (ThirdCategoryEntity oneLevelCategoryEntity : context.getThirdCategoryList()) {

            // 发起请求，获取document
            Document document = requestGet(MessageFormat.format(LEVEL2_URL, oneLevelCategoryEntity.getCategoryId()));

            // 解析
            Elements parentEle = document.getElementsByClass("col_nav clearfix");
            Elements childEle = parentEle.select("li").select("a");
            for (Element aEle : childEle) {
                ThirdCategoryEntity thirdCategory = new ThirdCategoryEntity();
                thirdCategory.setSource(context.getSource());
                thirdCategory.setLevel(2);
                thirdCategory.setStatus(StatusEnum.VALID.getCode());
                thirdCategory.setPid(oneLevelCategoryEntity.getId());
                thirdCategory.setName(aEle.text());
                thirdCategory.setCategoryId(StringUtil.trimFirstAndLastChar(aEle.attributes().get("href"), "/"));
                twoLevelCategoryList.add(thirdCategory);
            }
        }

        // 填充
        context.setThirdCategoryList(twoLevelCategoryList);

        // 保存
        saveOrUpdate(context);
    }

}
